package com.dongbei.baseproject.ui.splash

import android.annotation.SuppressLint
import android.content.Intent
import androidx.databinding.DataBindingUtil.setContentView
import com.dongbei.baseproject.R
import com.dongbei.baseproject.base.BaseActivity
import com.dongbei.baseproject.databinding.ActivitySplashBinding
import com.dongbei.baseproject.ui.home.HomeActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@SuppressLint("CustomSplashScreen")
@AndroidEntryPoint
class SplashActivity : BaseActivity() {
    private val splashDuration = 4000L // 4秒倒计时
    private var splashJob: Job? = null
    private lateinit var mBinding: ActivitySplashBinding


    override fun getLayoutId() = R.layout.activity_splash

    override fun initView() {
        mBinding = setContentView(this, getLayoutId())
    }

    override fun initData() {
        startSplashCountdown()
    }

    override fun initEvent() {
        mBinding.tvSkip.setOnClickListener {
            splashJob?.cancel() // 取消倒计时任务
            navigateToMainActivity() // 立即跳转到主页面
        }
    }

    private fun startSplashCountdown() {
        splashJob = CoroutineScope(Dispatchers.Main).launch {
            delay(splashDuration) // 延迟 4 秒
            navigateToMainActivity() // 跳转到主页面
        }
    }

    // 跳转到主页面的函数
    private fun navigateToMainActivity() {
        val intent = Intent(this, HomeActivity::class.java)
        startActivity(intent)
        finish() // 结束当前Activity
    }

    override fun onDestroy() {
        super.onDestroy()
        splashJob?.cancel() // 确保倒计时任务在 Activity 销毁时被取消
    }
}